<template>
  <div class="btn" @click="toLike()">
    <i
      :class="[
        isLike ? 'active' : '',
        type === 'collect' ? 'icon-ic-Collection' : '',
        type === 'support' ? 'icon-ic-like' : ''
      ]"
      class="iconfont"
    />
  </div>
</template>

<script>
import { checkUserData } from '~/assets/js/util'

export default {
  name: 'BtnLike',
  props: {
    articleData: {
      type: Object,
      default: () => {}
    },
    type: {
      type: String,
      default: () => ''
    }
  },
  data() {
    return {
      isLike: false
    }
  },
  computed: {
    userData() {
      return this.$store.state.user.userData
    }
  },
  mounted() {
    if (this.type === 'collect' && this.userData) {
      this.isLike = this.articleData.hasCollect
    } else if (this.type === 'support' && this.userData) {
      this.isLike = this.articleData.hasSupport
    }
  },
  methods: {
    async toLike() {
      const res = checkUserData(this)
      if (!res) return
      const params = {
        choice: this.type,
        id: this.articleData.id,
        targetUserId: this.articleData.userId,
        title: this.articleData.title,
        userId: this.userData.userId
      }
      const method = this.isLike ? 'delete' : 'post'
      const data = await this.$request({
        context: this,
        method,
        url: `article/like`,
        params
      })
      if (!data) return
      this.isLike = !this.isLike
      this.$message.success('操作成功！')
    }
  }
}
</script>

<style scoped lang="scss">
@import "~assets/css/public";
.btn {
  width: 40px;
  height: 36px;
  overflow: hidden;
  background: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 12px;
  cursor: pointer;

  i.iconfont {
    color: #ccc;
  }
  i.iconfont.active {
    color: $theme-color;
  }
}
</style>
